'use strict'

let fs = require('fs');
let router = require('koa-router')();

function getFiles(filePath) {
    let tmpPath = filePath || __dirname;
    let tmpFiles = fs.readdirSync(tmpPath);
    let files = tmpFiles.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    })
    return files;
}

function resgin(router, files) {
    files.filter(item => {
        let obj = require(__dirname + '/' + item);

        for (let key in obj) {
            let tmpArr = key.split(' ');

            let tmpMethor = tmpArr[0];
            let tmpUrl = tmpArr[1];
            let tmpFunction = obj[key];

            if (tmpMethor === 'get') {
                router.get(tmpUrl, tmpFunction);
            } else if (tmpMethor === 'post') {
                router.post(tmpUrl, tmpFunction);
            } else if (tmpMethor === 'put') {
                router.put(tmpUrl, tmpFunction);
            } else if (tmpMethor === 'delete') {
                router.delete(tmpUrl, tmpFunction);
            }
        }
    })
    return router.routes();
}

module.exports = function () {
    let files = getFiles();
    let fn = resgin(router, files);
    return fn;
}